class User < ActiveRecord::Base
	
	extend Permissible
	
	attr_accessible :first_name, :last_name, :about, :matriculation_number, :email, :password, 
		:password_confirmation, :preferred_locale, :user_group_id, :last_login, 
		:created_by, :updated_by
	
	translates :about
	
	has_secure_password
  
    # Validations:
	validates :matriculation_number, :numericality => { :greater_than => 0, :allow_blank => true }
	VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
	validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, 
		uniqueness: { case_sensitive: false }
	validates :user_group_id, presence: true
	
	#TODO: Store min. pw length value in config file?
	validates :password, length: { minimum: 6 }, if: :password_changed?
	validates :password, presence: true, on: :create
	
    # Relationships:
	belongs_to :user_group
	has_and_belongs_to_many :permissions
	
	before_create :create_remember_token
	
	# Ensure email is lower-case to avoid duplicate emails, since uniqueness enforcement on the DB
	# level is case-sensitive.
	before_save { |user| user.email = email.downcase }
	
	
	def self.create_with_default_permissions(params)
		user = User.create(params)
		
		if user.errors.none?
			create_default_owner_permissions(user, user)	# current_user isn't set 
		end
		
		return user
	end
	
	def name
		if first_name.empty? and last_name.empty?
			email
		else 
			"#{first_name} #{last_name}".rstrip
		end
	end
	
	def guest?
		false
	end
		
	def admin? 
		user_group.name.downcase == 'administrators'
	end
	
	def to_s
		"#{name} (##{id})"
	end
	
	private

		# Creates a remember token used to identify a user again after the browser has been closed.
		def create_remember_token
			self.remember_token = SecureRandom.urlsafe_base64
		end
	
		def password_changed?
			!self.password.blank?
		end	
		
end
